using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;

namespace Code5Systems.FormMaster
{

	public partial class CascadeHandler : System.Web.UI.Page
	{
		
		protected void Page_Load(object sender, System.EventArgs e)
		{
			Response.ContentType = "text/xml";
			
			List<ListItem> items = null;
			string serialized = default(string);
			int moduleId = default(int);
			int.TryParse(Utility.CleanInputAll(Request["moduleid"]), out moduleId);
			string targetId = Utility.CleanInputAll(Request["targetid"]);
			string category = Utility.CleanInputAll(Request["category"]);
			
			Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(moduleId);
			
			Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo = objFormCtl.GetFormControlInfo(targetId);
			
			if (!string.IsNullOrEmpty(objFormControlInfo.FillListItemText))
			{
				DataTable dt = objFormCtl.GetQueryData(objFormControlInfo.ConnectionString, objFormControlInfo.FieldQuery);
				items = new List<ListItem>();
				if (dt.Columns.Contains("Results"))
				{
					if (category == "0")
					{
						items.Add(new ListItem(objFormControlInfo.PromptText, ""));
					}
				}
				else if (dt.Columns.Contains("Category"))
				{
					objFormControlInfo.ListItems.Clear();
					foreach (DataRow row in dt.Rows)
					{
						objFormControlInfo.ListItems.Add(new Code5Systems.FormMaster.Business.FMListItem((string) (row[objFormControlInfo.FillListItemText].ToString()), (string) (row[objFormControlInfo.FillListItemValue].ToString()), System.Convert.ToBoolean(row["Category"].ToString())));
					}
					
					items = (from Code5Systems.FormMaster.Business.FMListItem i in objFormControlInfo.ListItems
					where (i.Category == category)
					select i.ListItem).ToList();
					if (items.Count > 0)
					{
						items.Insert(0, new ListItem(objFormControlInfo.SelectText, "0"));
					}
				}
				else
				{
					if (dt.Columns.Contains(objFormControlInfo.FillListItemText))
					{
						items.Add(new ListItem(objFormControlInfo.SelectText, "0"));
						foreach (DataRow row in dt.Rows)
						{
							items.Add(new ListItem((row[objFormControlInfo.FillListItemText]).ToString(), (row[objFormControlInfo.FillListItemValue]).ToString()));
						}
					}
				}
			}
			else
			{
				items = (from Code5Systems.FormMaster.Business.FMListItem i in objFormControlInfo.ListItems
				where (i.Category == category)
				select i.ListItem).ToList();
				items.Insert(0, new ListItem(objFormControlInfo.SelectText, "0"));
			}
			serialized = (string) (Utility.XmlSerialize<List<ListItem>>(items));
			Response.Write(serialized);
			Response.End();
		}
		
	}
	
}
